package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140"); // wht6.cn
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        Channel c = con.createChannel();
        // 创建队列 hello-world，如果队列已经存在，不会重复创建
        c.queueDeclare("task_queue",true,false,false,null);

        // 创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            public void handle(String consumerTag, Delivery message) throws IOException {
                byte[] a = message.getBody();
                String s = new String(a);
                System.out.println("收到： "+s); // "ag.d..sfd.fs...gs..."
                // 模拟耗时消息
                // 遍历字符串，找 '.' 字符，每找到一个暂停一秒
                for (int i = 0; i < s.length(); i++) {
                    if ('.' == s.charAt(i)) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                //发送回执
                // c.basicAck(回执, 是否对之前收到的所有消息一起进行确认);
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("---------------------------消息处理结束");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            public void handle(String consumerTag) throws IOException {
            }
        };

        // 每次只收一条消息，处理完之前不收下一条
        c.basicQos(1);

        // 接收消息，收到的消息会传递到一个回调对象去处理
        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);
    }
}
